﻿//#define TEST_SDK

#if (!UNITY_EDITOR || TEST_SDK) && WEIXINMINIGAME

using Cysharp.Threading.Tasks;
using KuiHuaBaoDian.SDK.Serializable;
using WeChatWASM;

namespace KuiHuaBaoDian.SDK {

    public static partial class API {

        private partial class Implementation {

            private UniTaskCompletionSource<bool> m_TaskSource;

            private RewardedADSetting m_Setting;

            private static WXRewardedVideoAd m_Video;

            public UniTask InitializeRewardedAD(RewardedADSetting setting) {
                m_Setting = setting;
                UnityEngine.Debug.Log(m_Setting.ID);
                m_Video = WXBase.CreateRewardedVideoAd(new WXCreateRewardedVideoAdParam { adUnitId = m_Setting.ID, multiton = true });
                m_Video.OnClose(res => {
                    // 小于 2.1.0 的基础库版本，res 是一个 undefined
                    if ((res != null && res.isEnded) || res == null) {
                        // 正常播放结束，可以下发游戏奖励
                        m_TaskSource.TrySetResult(true);
                    } else {
                        // 播放中途退出，不下发游戏奖励
                        m_TaskSource.TrySetResult(false);
                    }
                });
                return UniTask.CompletedTask;
            }

            public async UniTask<IAPI.IRewardedADResult> ShowRewardedAD(System.Action<IAPI.IRewardedADResult> onLoad = null) {
                if (m_TaskSource != null) {
                    return new RewardedADResult();
                }
                m_TaskSource = new UniTaskCompletionSource<bool>();
                var count = 0;
                if (m_Video != null) {
                    m_Video.Load(_ => {
                        onLoad?.Invoke(new RewardedADResult {
                            ID = m_Setting.ID,
                            State = true,
                        });
                        m_Video.Show(failed: response => {
                            UnityEngine.Debug.LogWarning(response.errMsg);
                            m_TaskSource.TrySetResult(true); // 有广告组件，加载到广告，但是播放失败，所以还是给了 true
                        });
                    }, failed: response => {
                        UnityEngine.Debug.LogWarning(response.errMsg);
                        m_TaskSource.TrySetResult(true); // 有广告组件，但是没有加载到广告，所以还是给了 true
                    });
                } else {
                    UnityEngine.Debug.LogWarning("没有广告组件");
                    m_TaskSource.TrySetResult(true);
                }
                var state = await m_TaskSource.Task;
                if (state) {
                    count = 1;
                }
                m_TaskSource = null;
                var result = new RewardedADResult {
                    ID = m_Setting.ID,
                    Count = count,
                    State = state
                };
                return result;
            }
        }
    }
}
#endif